package com.petsdar.utils;

import com.petsdar.pojo.Result;
import org.apache.log4j.Logger;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

/**
 * Created with IntelliJ IDEA
 * User: heroC
 * Date: 2020/7/1
 * Time: 11:38
 * Description: 创建全局唯一的Jedis连接池
 * Version: V1.0
 */
public class JedisPoolUtil {
    private static Logger log = Logger.getLogger(JedisPoolUtil.class);
    // jedis连接池
    private static JedisPool jedisPool;
    // ip地址
    private static String ip;
    // 连接密码
    private static String pwd;
    // 端口号
    private static int port;
    // 最大连接数
    private static int maxTotal;
    // 最大空闲连接数
    private static int maxIdle;
    // 最小空闲连接数
    private static int minIdle;

    // 静态代码块，最先加载，并执行一次，对变量进行初始化
    static {
        FileInputStream in = null;
        Properties properties = null;
        String path = JedisPoolUtil.class.getResource("../../../jedis-config.properties").getPath();
        try {
            in = new FileInputStream(path);
            properties = new Properties();
            properties.load(in);
        } catch (FileNotFoundException e) {
            log.error("jedis-config.properties文件找不到 {"+e.getClass().getName()+": "+e.getMessage()+"}");
        } catch (IOException e) {
            log.error("IO异常 {"+e.getClass().getName()+": "+e.getMessage()+"}");
        }

        if (properties!=null){
            ip = properties.getProperty("AUTH.IP");
            pwd = properties.getProperty("AUTH.PASS");
            port = Integer.parseInt(properties.getProperty("AUTH.PORT"));
            maxTotal = Integer.parseInt(properties.getProperty("AUTH.MAXTOTAL"));
            maxIdle = Integer.parseInt(properties.getProperty("AUTH.MAXIDLE"));
            minIdle = Integer.parseInt(properties.getProperty("AUTH.MINIDLE"));
        }else {
            log.error("jedis配置文件获取异常！");
            throw new RuntimeException("jedis配置文件获取异常！");
        }

        initJedisPool();
    }

    /**
     * 初始化redis池
     */
    private static void initJedisPool(){
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxTotal);
        config.setMaxIdle(maxIdle);
        config.setMinIdle(minIdle);
        jedisPool = new JedisPool(config, ip, port,5000, pwd);
    }

    // 获取池实例方法
    public static Jedis getJedis(){
        return jedisPool.getResource();
    }
}
